'''
Created on 2018年6月23日
发送请求
@author: dark
'''
from urllib import parse, request
from getFromFile import getCookieFromFile
from getFromPage import getStage


# 购买彩票
def postBuy(number):
    data = {
        'Action': 'AddChaseBetting',
        'data': {
            "before_issueNo":1,
            "before_eamings_cash":-1,
            "after_eamings_cash":-1,
            "before_earnings_rate":-1,
            "after_earnings_rate":-1,
            "isstop_afterwinning":1,
            "start_issueNo":str(getStage()),
            "lottery_code":"1303",
            "chase_money":3,
            "buy_count":2,
            "betting":[{"lottery_code":"1303",
                "play_detail_code":"1303F11",
                "betting_number":number,
                "betting_count":5,
                "betting_money":1,
                "betting_point":"19.40-7.00%",
                "betting_model":0.1}],
            "shceme":[{"issueNo": str(getStage()),
                       "graduation_count":1,
                       "money":1},
                       {"issueNo": str(getStage() + 1),
                        "graduation_count":2,
                        "money":2}]},
        'SourceName': 'PC'
        }
    headers = {
        'Connection': 'keep-alive',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Cookie': getCookieFromFile(),
        'Host': 'www.cpb02.com',
        'Origin': 'http://www.cpb02.com',
        'Referer': 'http://www.cpb02.com/lottery/PK10/1303',
        'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36'
        }
    url = 'http://www.cpb02.com/tools/ssc_ajax.ashx?A=AddChaseBetting&S=cpb&U=q929609968'
#     对数据进行编码
    data = parse.urlencode(data).encode(encoding='utf-8')
    req = request.Request(url=url, data=data, headers=headers)
    try:
        res = request.urlopen(req, timeout=10)
        res = res.read()
        res = res.decode(encoding='utf-8')
        print(res)
    except Exception as e:
        print(str(e))
        postBuy(number)
